/*
 * ExportarForm.java
 *
 * Created on 13 de julio de 2008, 04:21
 */

package View;
import Controller.BaseDeDatosController;
import Servicio.Proxy;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream; 
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author  Gigin
 */
public class ExportarForm extends javax.swing.JDialog {
    private PpalForm ppal;
    private BaseDeDatosController mBaseDeDatos;
    private Porcentaje porcentaje=new Porcentaje(0);
    private int returnValue;    
    int opcion;
    JFileChooser fileChooser;
    
    /** Creates new form ExportarForm */
    public ExportarForm(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        mBaseDeDatos = new BaseDeDatosController();
        initComponents();
        //this.jProgressBar1.setEnabled(false);
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton2 = new javax.swing.JButton();
        jButtonExportar = new javax.swing.JButton();
        jButtonImportar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jProgressBar1 = new javax.swing.JProgressBar();
        jLabel2 = new javax.swing.JLabel();
        jButtonSustituir = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jButton2.setFont(new java.awt.Font("Verdana", 1, 10));
        jButton2.setForeground(new java.awt.Color(94, 148, 189));
        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Botones/Volver_normal.gif"))); // NOI18N
        jButton2.setToolTipText("Volver a la pantalla principal");
        jButton2.setBorderPainted(false);
        jButton2.setContentAreaFilled(false);
        jButton2.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/Botones/Volver_deshabilitado.gif"))); // NOI18N
        jButton2.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/Botones/Volver_presionado.gif"))); // NOI18N
        jButton2.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/Botones/Volver_mouse.gif"))); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButtonExportar.setText("Exportar");
        jButtonExportar.setToolTipText("Exportar datos a un archivo");
        jButtonExportar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonExportarActionPerformed(evt);
            }
        });

        jButtonImportar.setText("Sincronizar");
        jButtonImportar.setToolTipText("importar datos desde archivo");
        jButtonImportar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonImportarActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Monotype Corsiva", 1, 24)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(94, 148, 189));
        jLabel1.setText("Seleccione una opción");

        jProgressBar1.setEnabled(false);

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Botones/logo_GTV4.gif"))); // NOI18N

        jButtonSustituir.setText("Sustiuir");
        jButtonSustituir.setToolTipText("Sustituye la base actual");
        jButtonSustituir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSustituirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButtonImportar, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 148, Short.MAX_VALUE)
                .addComponent(jButtonExportar, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 269, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jButtonSustituir, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addGap(38, 38, 38))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButtonSustituir, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel2))
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButtonImportar, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonExportar, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(34, 34, 34)
                .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents


//Copia un archivo desde src hasta dst.
 public void copy(File src, File dst) throws IOException {
        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(dst);
        
        
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    } 

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

        this.dispose();
}//GEN-LAST:event_jButton2ActionPerformed

private void jButtonExportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonExportarActionPerformed
JFileChooser fileChooser = new JFileChooser();
        int returnValue = fileChooser.showDialog(this,"Exportar");
        if (returnValue == JFileChooser.APPROVE_OPTION) {
          File selectedFile = fileChooser.getSelectedFile();
          fileChooser.getCurrentDirectory();
          File base2 = new File(selectedFile.getAbsolutePath());
          File base3 = new File(selectedFile.getAbsolutePath() + ".s3db");
          File baseCentral = new File("base.s3db");
                    if(base2.getAbsolutePath().indexOf(".s3db")>-1){
                        if(JOptionPane.showConfirmDialog(fileChooser, "¿Desea reemplazar el archivo seleccionado?")==0){
              
                    try {
                        if (mBaseDeDatos.copy(baseCentral, base2) == 1) {

                            JOptionPane.showMessageDialog(new JFrame(), "El archivo se guardo en " + selectedFile.getAbsolutePath(), "Atención!", JOptionPane.INFORMATION_MESSAGE);
                        }
                    } catch (IOException ex) {
                        Logger.getLogger(ExportarForm.class.getName()).log(Level.SEVERE, null, ex);
                        JOptionPane.showMessageDialog(new JFrame(), "Ha ocurrido un error. Por favor vuelva a intentarlo", "Atención!", JOptionPane.INFORMATION_MESSAGE);
                    }
}
                    }else{
                            if(base2.getAbsolutePath().indexOf(".")>-1){
                                JOptionPane.showMessageDialog(new JFrame(), "El archivo no es un archivo de SADC", "Atención!", JOptionPane.INFORMATION_MESSAGE);
                            
                            }else{
                    try {
                        if (mBaseDeDatos.copy(baseCentral, base3) == 1) {

                            JOptionPane.showMessageDialog(new JFrame(), "El archivo se guardo en " + selectedFile.getAbsolutePath(), "Atención!", JOptionPane.INFORMATION_MESSAGE);
                        }
                    } catch (IOException ex) {
                        JOptionPane.showMessageDialog(new JFrame(), "Ha ocurrido un error. Por favor vuelva a intentarlo", "Atención!", JOptionPane.INFORMATION_MESSAGE);
                        Logger.getLogger(ExportarForm.class.getName()).log(Level.SEVERE, null, ex);
                    }
               
                    
                    }
        
                    }
        }
}//GEN-LAST:event_jButtonExportarActionPerformed

private void jButtonImportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonImportarActionPerformed

    fileChooser = new JFileChooser();
    returnValue = fileChooser.showDialog(this,"Sincronizar");    
    opcion =0;
    if (returnValue == JFileChooser.APPROVE_OPTION) {
    File selectedFile = fileChooser.getSelectedFile();
    if (selectedFile.getName().indexOf(".s3db")>-1){
    jButtonImportar.setEnabled(false);
    jButton2.setEnabled(false);
    jButtonSustituir.setEnabled(false);
    this.jButtonExportar.setEnabled(false);
    
    //this.jProgressBar1.setEnabled(true);
    this.jProgressBar1.setStringPainted(true);
    porcentaje.setValor(0);
    
    Thread barraProgreso=new ThreadBarra("hola");
    Thread importar=new ThreadImportar("gola");
    barraProgreso.start();
    importar.start();
    }else
             JOptionPane.showMessageDialog(new JFrame(), "El archivo seleccionado no es un archivo SADC", "Atención!", JOptionPane.INFORMATION_MESSAGE);
    }                  
   //jButtonImportar.setEnabled(true);
   
   //this.jProgressBar1.setEnabled(false);
   
}//GEN-LAST:event_jButtonImportarActionPerformed

private void jButtonSustituirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSustituirActionPerformed
    fileChooser = new JFileChooser();
    returnValue = fileChooser.showDialog(this,"Sustituir");    
    opcion =0;
    if (returnValue == JFileChooser.APPROVE_OPTION) {
    File selectedFile = fileChooser.getSelectedFile();
    if (selectedFile.getName().indexOf(".s3db")>-1){
    jButtonImportar.setEnabled(false);
    jButton2.setEnabled(false);
    jButtonSustituir.setEnabled(false);
    this.jButtonExportar.setEnabled(false);
    File base2 = new File("base_back.s3db");
    File baseCentral = new File("base.s3db");
    try{
        mBaseDeDatos.copy(baseCentral, base2);
        File baseAsincrona;
        if (fileChooser.getCurrentDirectory().toString().indexOf("/")>=0) 
            baseAsincrona = new File(fileChooser.getCurrentDirectory() +"/" + selectedFile.getName());
        else baseAsincrona = new File(fileChooser.getCurrentDirectory() +"\\" + selectedFile.getName());
        mBaseDeDatos.copy(baseAsincrona, baseCentral);
        JOptionPane.showMessageDialog(new JFrame(), "La sustitución se ha realizado con éxito", "Atención!", JOptionPane.INFORMATION_MESSAGE);

    jButtonImportar.setEnabled(true);
    jButton2.setEnabled(true);
    jButtonSustituir.setEnabled(true);
    this.jButtonExportar.setEnabled(true);
    } catch (IOException ex) {
            Logger.getLogger(ExportarForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }else
             JOptionPane.showMessageDialog(new JFrame(), "El archivo seleccionado no es un archivo SADC", "Atención!", JOptionPane.INFORMATION_MESSAGE);
    }               
}//GEN-LAST:event_jButtonSustituirActionPerformed

class ThreadBarra extends Thread {
    public ThreadBarra (String str) {
        super(str);
    }
    public void run() {

        while (porcentaje.getValor()<100){
        jProgressBar1.setValue(porcentaje.getValor());
        jProgressBar1.repaint();
        Thread.yield();
        }
        jProgressBar1.setValue(porcentaje.getValor());
        jButtonImportar.setEnabled(true);
        jButtonExportar.setEnabled(true);
        jButton2.setEnabled(true);
        jProgressBar1.repaint();
        Thread.yield();
        
    }
    
}

class ThreadImportar extends Thread {
    public ThreadImportar(String str) {
        super(str);
    }
    public void run() {
             File base2 = new File("base2.s3db");
        File baseCentral = new File("base.s3db");
        try {
            if (mBaseDeDatos.copy(baseCentral, base2) == 1) {
    porcentaje.setValor(12);   
    Thread.yield();
                if (returnValue == JFileChooser.APPROVE_OPTION) {
                    File selectedFile = fileChooser.getSelectedFile();
                    if (selectedFile.getName().indexOf(".s3db")>-1){
                    //System.out.println(fileChooser.getCurrentDirectory() +"//" + selectedFile.getName());
                   File baseAsincrona;
                    if (fileChooser.getCurrentDirectory().toString().indexOf("/")>=0) 
                        baseAsincrona = new File(fileChooser.getCurrentDirectory() +"/" + selectedFile.getName());
                    else baseAsincrona = new File(fileChooser.getCurrentDirectory() +"\\" + selectedFile.getName());
                    try {
                        mBaseDeDatos.copy(baseAsincrona, baseCentral);
                    } catch (IOException ex) {
                        Logger.getLogger(ExportarForm.class.getName()).log(Level.SEVERE, null, ex);
                        JOptionPane.showMessageDialog(new JFrame(), "Ha ocurrido algún problema. Por favor vuelva a intentarlo", "Atención!", JOptionPane.INFORMATION_MESSAGE);
                        }
                }else{
                        JOptionPane.showMessageDialog(new JFrame(), "El archivo seleccionado no es un archivo SADC", "Atención!", JOptionPane.INFORMATION_MESSAGE);
                        opcion=1;
                }
                }else {
                    //JOptionPane.showMessageDialog(new JFrame(), "El archivo seleccionado no es un archivo SADC", "Atención!", JOptionPane.INFORMATION_MESSAGE);
                    System.out.println("no quiere hacer nada");
                    opcion = 1;
                }
            } else {
                JOptionPane.showMessageDialog(new JFrame(), "Ha ocurrido algún problema. Por favor vuelva a intentarlo", "Atención!", JOptionPane.INFORMATION_MESSAGE);
                System.out.println("No se Pudo importar nada");
            }
        } catch (IOException ex) {
            Logger.getLogger(ExportarForm.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        if (opcion==0){
   porcentaje.setValor(24);  
   Thread.yield();
        //mBaseDeDatos.cargarClientesNuevos();
        mBaseDeDatos.cargarCongresosNuevos(porcentaje);

        try {
            if (mBaseDeDatos.copy(base2, baseCentral) == 1) {
                System.out.println("Lo copio bien la segunda vez");
                }
        } catch (IOException ex) {
            Logger.getLogger(ExportarForm.class.getName()).log(Level.SEVERE, null, ex);
        }

        //mBaseDeDatos.cargarClientesViejos();
   porcentaje.setValor(54);  
   Thread.yield();
        mBaseDeDatos.cargarCongresosViejos();
   porcentaje.setValor(60);   
   Thread.yield();
        //mBaseDeDatos.agregarClientes();
   //porcentaje=85;    
   //Thread.yield();
        mBaseDeDatos.agregarCongresos(porcentaje);
    Proxy.Recargar();
   porcentaje.setValor(100);   
   Thread.yield();
        JOptionPane.showMessageDialog(new JFrame(), "La sincronización se ha realizado con éxito", "Atención!", JOptionPane.INFORMATION_MESSAGE);
    }else{
    System.out.println("No quiere Hacer nada");
    }
        
    }
    
}

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButtonExportar;
    private javax.swing.JButton jButtonImportar;
    private javax.swing.JButton jButtonSustituir;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JProgressBar jProgressBar1;
    // End of variables declaration//GEN-END:variables

}
